$(function () {
    // 给去注册帐号按钮绑定事件
    $('#link_reg').on('click', () => {
        $('.login-box').hide().siblings('.reg-box').show()
    })
    //给去登录按钮绑定事件
    $('#link_login').on('click', () => {
        $('.reg-box').hide().siblings('.login-box').show()
    })
    // 引入layui.form对象
    let form = layui.form
    // 引入layui.layer对象
    let layer = layui.layer
    form.verify({
        pwd: [
            /^[\S]{6,12}$/
            , '密码必须6到12位，且不能出现空格'
        ], repwd: function (value) {
            let pwd = $('.reg-box [name=password]').val()
            if (pwd !== value) {
                return '两次密码不一致'
            }
        }
    });

    // 注册事件
    $('#form_reg').on('submit', function (e) {
        e.preventDefault()

        let username = $('.reg-box [name=username]').val()
        let password = $('.reg-box [name=password]').val()
        axios.post('/api/reguser', `username=${username}&password=${password}`)
            .then(res => {
                layer.msg(res.data.message)
                if (res.data.status === 0) {
                    $('#link_login').click()
                }
            })
            .catch(err => {
                console.dir(err);
                layer.msg(err.message);
            })
    })
    //登录事件
    $('#form_login').on('submit', function (e) {
        e.preventDefault()

        let username = $('.login-box [name=username]').val()
        let password = $('.login-box [name=password]').val()
        axios.post('/api/login', `username=${username}&password=${password}`)
            .then(res => {
                layer.msg(res.data.message)
                if (res.data.status === 0) {
                    location.assign('../../index.html')
                }
            })
            .catch(err => {
                layer.msg(err.message);
            })
    })
})